package com.ezlcp.form.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ezlcp.commons.base.db.BaseService;
import com.ezlcp.commons.base.entity.JsonPageResult;
import com.ezlcp.commons.base.entity.JsonResult;
import com.ezlcp.commons.base.entity.QueryData;
import com.ezlcp.commons.base.search.QueryFilter;
import com.ezlcp.commons.base.search.QueryFilterBuilder;
import com.ezlcp.commons.constant.ListTypeEnum;
import com.ezlcp.commons.constant.StatusEnum;
import com.ezlcp.commons.tool.StringUtils;
import com.ezlcp.commons.utils.ContextUtil;
import com.ezlcp.form.entity.DataList;
import com.ezlcp.form.service.DataListServiceImpl;
import com.ezlcp.form.web.BaseController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/ezlcp/form/dataList")
@Tag(name = "查询列表定义")
public class DataListController extends BaseController<DataList> {
    @Resource
    DataListServiceImpl dataListService;

    @Operation(summary = "获取列表类型为表格的实例数据")
    @PostMapping("/getDataOfTable")
    public JsonPageResult getDataOfTable(@RequestBody QueryData queryData) {
        if (queryData == null || StringUtils.isEmpty(queryData.getListId())) {
            return JsonPageResult.getFail("common.paramError");
        }
        String listId = queryData.getListId();
        String key = queryData.getKey();
        String language=queryData.getLanguage();
        QueryFilter filter = QueryFilterBuilder.createQueryFilter(queryData);
        return dataListService.getDataOfTable(listId, filter, key,language);
    }

    @Operation(summary = "查看数据列表SQL")
    @PostMapping("/viewSql")
    public JsonResult viewSql(@RequestBody JSONObject object) {
        var list = object.getObject("dataList", DataList.class);
        if (list == null || list.getCols() == null || list.getCols().isEmpty() || StringUtils.isEmpty(list.getEntId())
                || StringUtils.isEmpty(list.getName())) {
            return JsonResult.Fail("common.paramError");
        }
        String sql = dataListService.getDataListSql(list);
        JsonResult result = JsonResult.getSuccessResult("common.handleSuccess");
        result.setData(sql);
        return result;
    }

    @Operation(summary = "发布数据列表")
    @PostMapping("/publish")
    public JsonResult publish(@Parameter(description = "主键Id") @RequestParam(value = "id") String id) {
        if (StringUtils.isEmpty(id)) {
            return JsonResult.Fail("common.paramError");
        }
        return dataListService.publish(id);
    }

    @Operation(summary = "获取列表视图类型")
    @GetMapping("/getListType")
    public JsonResult getListType() {
        JsonResult result = JsonResult.getSuccessResult("common.handleSuccess");
        var types = ListTypeEnum.values();
        JSONArray array = new JSONArray();
        for (var type : types) {
            array.add(type.toJsonObject());
        }
        result.setData(array);
        return result;
    }

    @Operation(summary = "保存数据列表信息")
    @PostMapping("/saveDataList")
    public JsonResult saveDataList(@RequestBody JSONObject object) {
        var list = object.getObject("dataList", DataList.class);
        String delIds = object.getString("deleteIds");
        if (list == null || list.getCols() == null || list.getCols().isEmpty() || StringUtils.isEmpty(list.getEntId())
                || StringUtils.isEmpty(list.getName())) {
            return JsonResult.Fail("common.paramError");
        }
        var oldList = dataListService.get(list.getId());
        if (oldList != null) {
            if (oldList.getSeq() != list.getSeq() || oldList.getStatus() == StatusEnum.deleted.getValue()) {
                return JsonResult.Fail("common.dataChange");
            }
        }
        JSONObject logData = new JSONObject();
        logData.put("new", list);
        logData.put("old", oldList);
        logService.saveSystemLog(getComment(), "save", list.getId(), JSON.toJSONString(logData));
        return dataListService.saveDataList(list, delIds);
    }

    @Operation(summary = "删除某个列表")
    @PostMapping("/delete")
    public JsonResult delete(@Parameter(description = "主键Id") @RequestParam("pkId") String pkId) {
        if (StringUtils.isEmpty(pkId)) {
            return JsonResult.Fail("common.paramError");
        }
        var dataList = dataListService.getById(pkId);
        if (dataList == null) {
            return JsonResult.Fail("common.paramError");
        }
        dataListService.delList(dataList);
        logService.saveSystemLog(getComment(), "delete", dataList.getId(), JSON.toJSONString(dataList));
        return JsonResult.getSuccessResult("common.handleSuccess");
    }

    @Override
    protected void handleFilter(QueryFilter filter) {
        String tenantId = ContextUtil.getCurrentTenantId();
        if (StringUtils.isNotEmpty(tenantId)) {
            filter.addQueryParam("Q_d.tenant_id_S_EQ", tenantId);
        }
    }

    @Override
    public JsonResult save(DataList entity, BindingResult validResult) throws Exception {
        return JsonPageResult.getFail("common.apiClose");
    }

    @Override
    public JsonPageResult getAll() {
        return JsonPageResult.getFail("common.apiClose");
    }

    @Override
    public JsonResult del(@RequestParam(value = "id") String id) {
        return JsonResult.Fail("common.apiClose");
    }

    @Override
    public BaseService getBaseService() {
        return dataListService;
    }

    @Override
    public String getComment() {
        return "列表定义";
    }
}